package com.wen.ui;

import com.wen.bean.Tasklist;
import com.wen.util.NetStatUtil;
import com.wen.util.TasklistUtil;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: wenxin
 * @Date: 2022/6/23 13:22
 * @Version: 1.0
 */
public class port {
    private JPanel rootPanel;
    private JTextField name_input;
    private JTextField port_input;
    private JTextField pid_input;
    private JButton findButton;
    private JButton closeButton;
    private JLabel lib1;
    private JLabel lib2;
    private JTable table1;
    private JPanel h;
    private JPanel c;
    private JTable table2;
    private JLabel lib3;
    private DefaultTableModel tModel1;
    private DefaultTableModel tModel2;
    private JFrame frame;
    JScrollPane scroll1;
    JScrollPane scroll2;
    private JPopupMenu m_popupMenu;
    private String mouseRight=null;


    public port() {
        intiComponent();
        bindButton();
        frame = new JFrame("windows端口查询");
        frame.setContentPane(rootPanel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        // 窗口居中
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation((d.width - frame.getSize().width) / 2,
                (d.height - frame.getSize().height) / 2);
        frame.setIconImage(new ImageIcon("resource/icon/icon1.png").getImage());
    }
    /**
     * 初始化窗体组件
     */
    private void intiComponent()
    {
        query();
        createPopupMenu();
        h.setBorder(new EmptyBorder(10,10,0,10));
        GridLayout layout=new GridLayout();
        //水平间距
        layout.setHgap(20);
        c.setLayout(layout);
        c.setBorder(new EmptyBorder(10,10,10,10));
        scroll1 = new JScrollPane(table1);
        c.add(scroll1);
        scroll2 = new JScrollPane(table2);
        c.add(scroll2);
    }

    private void query(){
        query(null,null,null);
    }
    private void query(String name,String port,String pid){
        Object[][] tasklists=getTasklist(name,port,pid);
        setTable1Data(tasklists);
        Object[][] netstatList=getStatNetList(name,port,pid);
        setTable2Data(netstatList);
    }


    private void setTable1Data(Object[][] data){
        String[] columnNames1 =
                { "映像名称", "PID", "会话名", "会话", "内存使用"};
        if(tModel1==null){
            tModel1=new DefaultTableModel(data,columnNames1);
            table1=new JTable(tModel1) {
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
        }
        tModel1.setDataVector(data,columnNames1);
    }
    private void setTable2Data(Object[][] data){
        String[] columnNames2 =
                { "协议", "本地地址", "外部地址", "状态", "PID"};
        if(tModel2==null){
            tModel2=new DefaultTableModel(data,columnNames2);
            table2=new JTable(tModel2) {
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
        }
        tModel2.setDataVector(data,columnNames2);
    }

    private void bindButton(){
        findButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String name=name_input.getText();
                String port=port_input.getText();
                String pid=pid_input.getText();
                query(name,port,pid);
            }
        });
        //表格1右击
        table1.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mouseRight="table1";
                jTableMouseClicked(evt,table1);
            }
        });
        //表格2右击
        table2.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                mouseRight="table2";
                jTableMouseClicked(evt,table2);
            }
        });

    }

    private void createPopupMenu() {
        m_popupMenu = new JPopupMenu();
        JMenuItem delMenItem = new JMenuItem();
        delMenItem.setText("  关闭  ");
        delMenItem.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String pid="";
                if(mouseRight.equals("table1")){
                    pid= (String) table1.getValueAt(table1.getSelectedRow(),1);
                }else if(mouseRight.equals("table2")){
                    pid= (String) table2.getValueAt(table2.getSelectedRow(),4);
                }
                int result = JOptionPane.showConfirmDialog(frame,"确定要关闭?", "确认",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
                if(result == JOptionPane.YES_OPTION){
                    System.out.println("是");
                }
            }
        });
        m_popupMenu.add(delMenItem);
    }
    private void jTableMouseClicked(java.awt.event.MouseEvent evt,JTable table) {
        mouseRightButtonClick(evt,table);
    }
    //鼠标右键点击事件
    private void mouseRightButtonClick(java.awt.event.MouseEvent evt,JTable table) {
        //判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键
        if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
            //通过点击位置找到点击为表格中的行
            int focusedRowIndex = table.rowAtPoint(evt.getPoint());
            if (focusedRowIndex == -1) {
                return;
            }
            //将表格所选项设为当前右键点击的行
            table.setRowSelectionInterval(focusedRowIndex, focusedRowIndex);
            //弹出菜单
            m_popupMenu.show(table, evt.getX(), evt.getY());
        }
    }
    /**
     * 结束进程
     */
    public void killProcess(String pid) {
        Runtime runtime = Runtime.getRuntime();
        try {
            //taskkill /pid 10580 -f
            Process tasklist = runtime.exec("taskkill /pid " + pid + " -f");
            System.out.println("进程关闭成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拿到PID对应的进程名
     * @return
     */
    public static Object[][] getTasklist(String name,String port,String pid) {
        List<Tasklist> tasklists=new ArrayList<>();
        Runtime runtime = Runtime.getRuntime();
        int index = 0;
        try {
            StringBuffer exec=new StringBuffer("tasklist");
            Boolean flag=false;
            if(pid!=null&&!"".equals(pid)){
                exec.append(" | findstr ").append(pid);
                flag=true;
            }else if(name!=null&&!"".equals(name)){
                exec.append(" | findstr ").append(name);
                flag=true;
            }
            Process tasklist = runtime.exec(new String[]{"cmd", "/c", exec.toString()});
            BufferedReader reader = new BufferedReader(new InputStreamReader(tasklist.getInputStream(), "GBK"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (flag==true||index >= 3) {
                    Tasklist task = TasklistUtil.getTaskList(line);
                    tasklists.add(task);
                }
                index++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object[][] num=new Object[tasklists.size()][5];
        for (int i=0;i<tasklists.size();i++){
            num[i][0]=tasklists.get(i).getProcessName();
            num[i][1]=tasklists.get(i).getPid();
            num[i][2]=tasklists.get(i).getSessionName();
            num[i][3]=tasklists.get(i).getSessionNum();
            num[i][4]=tasklists.get(i).getMemory();
        }
        return num;
    }


    public static Object[][] getStatNetList(String name,String port,String pid) {
        List<String[]> netstatList=new ArrayList<>();
        Runtime runtime = Runtime.getRuntime();
        int index = 0;
        try {
            StringBuffer exec=new StringBuffer("netstat -ano");
            if(pid!=null&&!"".equals(pid)){
                exec.append(" | findstr \"").append(pid).append("\"");
            }else if(port!=null&&!"".equals(port)){
                exec.append(" | findstr \"").append(port).append("\"");
            }


            Process tasklist = runtime.exec(new String[]{"cmd", "/c", exec.toString()});
            BufferedReader reader = new BufferedReader(new InputStreamReader(tasklist.getInputStream(), "GBK"));
            String line = null;
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                if (index >= 3) {
                    String[] netstst =NetStatUtil.getNetStatList(line);
                    netstatList.add(netstst);
                }
                index++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object[][] num2=new Object[netstatList.size()][5];
        for (int i=0;i<netstatList.size();i++){
            num2[i]=netstatList.get(i);
        }
        return num2;
    }

}
